<template>
    <el-main class="main-container">
        <!-- 头部区域 -->
        <div class="header-wrapper">
            <div class="page-title">
                <h1>用户管理</h1>
                <p>管理系统用户和权限</p>
            </div>
            <div class="user-profile">
                <el-dropdown trigger="hover" @command="handleDropdownCommand">
                    <div class="avatar-wrapper">
                        <el-badge :value="onlineUserCount" :max="99" :hidden="!onlineUserCount">
                            <el-avatar class="user-avatar" :src="$store.state.user.headPicture"
                                @error="handleAvatarError">
                                <i class="el-icon-user-solid"></i>
                            </el-avatar>
                        </el-badge>
                        <div class="user-info">
                            <span class="user-name">{{ $store.state.user.name || '管理员' }}</span>
                            <span class="user-uid">系统管理员</span>
                        </div>
                        <i class="el-icon-arrow-down dropdown-icon"></i>
                    </div>
                    <el-dropdown-menu slot="dropdown" class="custom-dropdown">
                        <el-dropdown-item command="profile" icon="el-icon-user">个人资料</el-dropdown-item>
                        <el-dropdown-item command="upload" icon="el-icon-camera">更换头像</el-dropdown-item>
                        <el-dropdown-item command="settings" icon="el-icon-setting">系统设置</el-dropdown-item>
                        <el-dropdown-item divided command="logout" icon="el-icon-switch-button">退出登录</el-dropdown-item>
                    </el-dropdown-menu>
                </el-dropdown>
            </div>
        </div>
        <!-- 统计卡片区域 -->
        <div class="stats-section">
            <div class="stat-card">
                <div class="stat-icon total">
                    <i class="el-icon-user"></i>
                </div>
                <div class="stat-content">
                    <div class="stat-value">{{ displayTotal }}</div>
                    <div class="stat-label">总用户数</div>
                </div>
            </div>
            <div class="stat-card">
                <div class="stat-icon active">
                    <i class="el-icon-check"></i>
                </div>
                <div class="stat-content">
                    <div class="stat-value">{{ activeUserCount }}</div>
                    <div class="stat-label">活跃用户</div>
                </div>
            </div>
            <div class="stat-card">
                <div class="stat-icon inactive">
                    <i class="el-icon-close"></i>
                </div>
                <div class="stat-content">
                    <div class="stat-value">{{ inactiveUserCount }}</div>
                    <div class="stat-label">禁用用户</div>
                </div>
            </div>
            <div class="stat-card">
                <div class="stat-icon online">
                    <i class="el-icon-connection"></i>
                </div>
                <div class="stat-content">
                    <div class="stat-value">{{ onlineUserCount }}</div>
                    <div class="stat-label">在线用户</div>
                </div>
            </div>
        </div>
        <!-- 搜索和操作区域 -->
        <div class="action-section">
            <div class="search-filters">
                <el-select v-model="searchType" placeholder="搜索类型" class="search-type-select">
                    <el-option label="用户名" value="NAME"></el-option>
                    <el-option label="邮箱" value="EMAIL"></el-option>
                    <el-option label="手机号" value="MOBILE_PHONE"></el-option>
                </el-select>
                <el-input v-model="searchValue" placeholder="请输入搜索内容..." clearable class="search-input"
                    @clear="handleClear" @keyup.enter="handleSearch">
                    <i slot="prefix" class="el-input__icon el-icon-search"></i>
                </el-input>
                <el-select v-model="filters.status" placeholder="选择状态" clearable class="filter-select">
                    <el-option label="全部状态" value=""></el-option>
                    <el-option label="已启用" :value="0"></el-option>
                    <el-option label="已禁用" :value="1"></el-option>
                </el-select>
                <el-select v-model="filters.uid" placeholder="选择角色" clearable class="filter-select">
                    <el-option label="全部角色" value=""></el-option>
                    <el-option label="管理员" value="admin"></el-option>
                    <el-option label="普通用户" value="user"></el-option>
                    <el-option label="VIP用户" value="vip"></el-option>
                </el-select>
                <el-button type="primary" icon="el-icon-search" @click="handleSearch" :loading="listLoading">
                    搜索
                </el-button>
                <el-button icon="el-icon-refresh" @click="handleRefresh">重置</el-button>
            </div>
            <div class="action-buttons">
                <el-button type="success" icon="el-icon-plus" @click="handleAdd" class="add-btn">
                    添加用户
                </el-button>
                <el-button type="danger" icon="el-icon-delete" :disabled="multipleSelection.length === 0"
                    @click="handleBatchDelete" class="batch-delete-btn">
                    批量删除 ({{ multipleSelection.length }})
                </el-button>
                <el-button type="info" icon="el-icon-download" @click="handleExport">
                    导出数据
                </el-button>
            </div>
        </div>
        <!-- 表格区域 -->
        <div class="table-section">
            <el-table v-loading="listLoading" :data="currentTableData" @selection-change="handleSelectionChange"
                class="custom-table" stripe :row-class-name="tableRowClassName" :header-cell-style="headerCellStyle"
                empty-text="暂无用户数据" element-loading-text="加载中...">
                <el-table-column type="selection" width="55" align="center" />
                <el-table-column prop="id" label="ID" width="80" align="center">
                    <template slot-scope="{ row }">
                        <el-tag size="mini" type="info">#{{ row.id }}</el-tag>
                    </template>
                </el-table-column>
                <el-table-column label="头像" width="100" align="center">
                    <template slot-scope="{ row }">
                        <div class="avatar-cell">
                            <el-avatar :src="row.headPicture" :size="60" class="user-table-avatar">
                                <i class="el-icon-user-solid"></i>
                            </el-avatar>
                            <div v-if="row.isOnline" class="online-indicator"></div>
                        </div>
                    </template>
                </el-table-column>
                <el-table-column prop="name" label="用户名" min-width="180" show-overflow-tooltip>
                    <template slot-scope="{ row }">
                        <div class="user-name-cell">
                            <span class="user-name">{{ row.name }}</span>
                            <div class="user-tags">
                                <el-tag v-if="row.uid === 'vip'" size="mini" type="warning">VIP</el-tag>
                                <el-tag v-if="row.uid === 'admin'" size="mini" type="danger">管理员</el-tag>
                                <el-tag v-if="row.isNewUser" size="mini" type="success">新用户</el-tag>
                            </div>
                        </div>
                    </template>
                </el-table-column>
                <el-table-column prop="email" label="邮箱" width="200" show-overflow-tooltip>
                    <template slot-scope="{ row }">
                        <span class="email-text">{{ row.email || '未设置' }}</span>
                    </template>
                </el-table-column>
                <el-table-column prop="mobilePhone" label="手机号" width="140" align="center">
                    <template slot-scope="{ row }">
                        <span class="phone-text">{{ formatPhone(row.mobilePhone) }}</span>
                    </template>
                </el-table-column>
                <el-table-column prop="uid" label="角色" width="120" align="center">
                    <template slot-scope="{ row }">
                        <el-tag :type="getRoleColor(row.uid)" size="small">{{ getRoleText(row.uid) }}</el-tag>
                    </template>
                </el-table-column>
                <el-table-column prop="status" label="状态" width="100" align="center">
                    <template slot-scope="{ row }">
                        <el-switch v-model="row.status" :active-value="0" :inactive-value="1" active-color="#13ce66"
                            inactive-color="#ff4949" @change="handleStatusChange(row.id, row.status)">
                        </el-switch>
                    </template>
                </el-table-column>
                <el-table-column prop="lastLoginTime" label="最后登录" width="160" align="center">
                    <template slot-scope="{ row }">
                        <span class="time-text">{{ formatDate(row.lastLoginTime) }}</span>
                    </template>
                </el-table-column>
                <el-table-column prop="createTime" label="创建时间" width="160" align="center">
                    <template slot-scope="{ row }">
                        <span class="time-text">{{ formatDate(row.createTime) }}</span>
                    </template>
                </el-table-column>
                <el-table-column label="操作" width="220" fixed="right" align="center">
                    <template slot-scope="{ row }">
                        <div class="action-buttons-cell">
                            <el-tooltip content="查看详情" placement="top">
                                <el-button size="mini" type="info" icon="el-icon-view" circle
                                    @click="handleView(row)"></el-button>
                            </el-tooltip>
                            <el-tooltip content="编辑" placement="top">
                                <el-button size="mini" type="primary" icon="el-icon-edit" circle
                                    @click="handleEdit(row.id)"></el-button>
                            </el-tooltip>
                            <el-tooltip content="重置密码" placement="top">
                                <el-button size="mini" type="warning" icon="el-icon-key" circle
                                    @click="handleResetPassword(row.id)"></el-button>
                            </el-tooltip>
                            <el-tooltip content="删除" placement="top">
                                <el-button size="mini" type="danger" icon="el-icon-delete" circle
                                    @click="handleDelete(row.id)"></el-button>
                            </el-tooltip>
                        </div>
                    </template>
                </el-table-column>
            </el-table>
        </div>
        <!-- 分页区域 -->
        <div class="pagination-section">
            <div class="pagination-info">
                <span>共 {{ displayTotal }} 条记录，每页显示 {{ pageSize }} 条</span>
            </div>
            <el-pagination :current-page.sync="currentPage" :page-sizes="[10, 20, 50, 100]" :page-size.sync="pageSize"
                :total="displayTotal" layout="sizes, prev, pager, next, jumper" @size-change="handleSizeChange"
                @current-change="handlePageChange" background :pager-count="5" />
        </div>
        <!-- 头像上传 -->
        <input type="file" ref="fileInput" @change="handleFileChange" style="display: none" accept="image/*" />
        <!-- 用户详情弹窗 -->
        <el-dialog title="用户详情" :visible.sync="detailDialogVisible" width="600px" :before-close="closeDetailDialog">
            <div v-if="currentUser" class="user-detail">
                <div class="detail-header">
                    <div class="detail-avatar">
                        <el-avatar :src="currentUser.headPicture" :size="100" class="detail-user-avatar">
                            <i class="el-icon-user-solid"></i>
                        </el-avatar>
                        <div v-if="currentUser.isOnline" class="online-badge">在线</div>
                    </div>
                    <div class="detail-info">
                        <h3>{{ currentUser.name }}</h3>
                        <p class="user-email">{{ currentUser.email || '未设置邮箱' }}</p>
                        <div class="user-status-tags">
                            <el-tag :type="getStatusType(currentUser.status)">{{ getStatusText(currentUser.status)
                                }}</el-tag>
                            <el-tag :type="getRoleColor(currentUser.uid)">{{ getRoleText(currentUser.uid) }}</el-tag>
                        </div>
                    </div>
                </div>
                <el-divider></el-divider>
                <div class="detail-content">
                    <el-row :gutter="20">
                        <el-col :span="12">
                            <p><strong>手机号：</strong>{{ formatPhone(currentUser.mobilePhone) }}</p>
                            <p><strong>用户ID：</strong>#{{ currentUser.id }}</p>
                            <p><strong>注册时间：</strong>{{ formatDate(currentUser.createTime) }}</p>
                            <p><strong>性别：</strong>{{ currentUser.sex === '男' ? '男' : currentUser.sex === '女' ? '女' :
                                '未设置' }}
                            </p>
                            <p><strong>联系地址：</strong>{{ currentUser.address || '未设置' }}</p>
                        </el-col>
                        <el-col :span="12">
                            <p><strong>最后登录：</strong>{{ formatDate(currentUser.lastLoginTime) }}</p>
                            <p><strong>登录次数：</strong>{{ currentUser.loginCount || 0 }}</p>
                            <p><strong>账户余额：</strong>{{ currentUser.userMoney || 0 }} 元</p>
                            <p><strong>商品数量：</strong>{{ currentUser.goodsNum || 0 }} 件</p>
                            <p><strong>车辆数量：</strong>{{ currentUser.carNum || 0 }} 辆</p>
                        </el-col>
                    </el-row>
                    <div v-if="currentUser.bio" class="user-bio">
                        <p><strong>个人简介：</strong></p>
                        <p>{{ currentUser.bio }}</p>
                    </div>
                </div>
            </div>
            <span slot="footer" class="dialog-footer">
                <el-button @click="detailDialogVisible = false">关闭</el-button>
                <el-button type="primary" @click="handleEdit(currentUser.id)">编辑用户</el-button>
            </span>
        </el-dialog>
    </el-main>
</template>
<script>
import {
    getUserList, handleDeleteUser, batchDelete, UpUser, getUserById,
    getCurrentActiveUserNumberByDate, GetByImportanceKey, getActiveUserNumberByDate,
    modifyStatus
} from '@/api/admin/User'
import { upload } from '@/api/common/common'
export default {
    name: 'UserManagement',
    data() {
        return {
            searchType: '用户名', // 默认搜索类型：用户名
            searchValue: '', // 统一搜索输入值
            currentPage: 1,
            pageSize: 10,
            total: 0,
            filters: {
                name: '',
                status: '',
                uid: ''
            },
            isPolling: false,
            isLoading: false,
            pollingTimer: null,
            listLoading: false,
            tableData: [],
            searchResultData: [],
            multipleSelection: [],
            detailDialogVisible: false,
            currentUser: null,
            onlineUserCount: 0,
            activeUserCount: 0,
            inactiveUserCount: 0,
            isSearching: false,
            pollingInterval: 5000, // 5秒轮询间隔
            errorCount: 0, // 错误计数，用于重试机制
            maxErrorCount: 3 // 最大错误次数
        }
    },
    computed: {
        currentTableData() {
            if (this.isSearching) {
                const start = (this.currentPage - 1) * this.pageSize;
                const end = this.currentPage * this.pageSize;
                return this.searchResultData.slice(start, end);
            } else {
                return this.tableData;
            }
        },
        displayTotal() {
            return this.isSearching ? this.searchResultData.length : this.total;
        },
        headerCellStyle() {
            return {
                background: 'linear-gradient(135deg, #667eea 0%, #764ba2 100%)',
                color: '#fff',
                fontWeight: '600',
                fontSize: '14px'
            };
        },
        // 轮询状态显示文本
        pollingStatusText() {
            return this.isPolling ? '停止轮询' : '开始轮询';
        },
        // 轮询状态图标
        pollingStatusIcon() {
            return this.isPolling ? 'el-icon-video-pause' : 'el-icon-video-play';
        }
    },
    methods: {
        // 切换轮询状态 - 修复版本
        togglePolling() {
            if (this.isPolling) {
                this.stopPolling();
                this.$message.success('已停止轮询');
            } else {
                this.startPolling();
                this.$message.success('开始轮询在线用户数据');
            }
        },
        // 启动轮询 - 修复版本
        async startPolling() {
            this.isPolling = true;
            this.errorCount = 0; // 重置错误计数
            console.log('启动轮询...');
            // 立即执行一次数据获取
            await this.fetchData();
            // 启动定时轮询
            this.scheduleNextPoll();
        },
        // 停止轮询 - 修复版本
        stopPolling() {
            this.isPolling = false;
            if (this.pollingTimer) {
                clearTimeout(this.pollingTimer);
                this.pollingTimer = null;
            }
            console.log('停止轮询');
        },
        // 安排下一次轮询 - 修复版本
        scheduleNextPoll() {
            if (!this.isPolling) return;
            this.pollingTimer = setTimeout(async () => {
                if (this.isPolling) {
                    await this.fetchData();
                    this.scheduleNextPoll(); // 递归调用，实现链式轮询
                }
            }, this.pollingInterval);
        },
        // 获取数据 - 修复版本（需要导入正确的API）
        async fetchData() {
            // 如果正在加载中，跳过本次轮询
            if (this.isLoading) {
                console.log('跳过本次轮询：正在加载中');
                return;
            }
            this.isLoading = true;
            try {
                // console.log('执行轮询请求...');
                // 使用正确的API函数（确保已导入）
                const today = new Date().toISOString().split('T')[0];
                const activeRes = await getCurrentActiveUserNumberByDate(today);
                // console.log('轮询响应:', activeRes);
                if (activeRes && activeRes.data && activeRes.data.data !== undefined) {
                    // 更新在线用户数
                    this.onlineUserCount = activeRes.data.data;
                    this.errorCount = 0; // 重置错误计数
                } else {
                    throw new Error('无效的响应数据');
                }
            } catch (error) {
                this.errorCount++;
                console.error(`轮询请求失败 (${this.errorCount}/${this.maxErrorCount}):`, error);
                // 如果连续错误次数超过阈值，停止轮询
                if (this.errorCount >= this.maxErrorCount) {
                    this.$message.error(`轮询失败次数过多，已自动停止`);
                    this.stopPolling();
                } else {
                    this.$message.warning(`轮询失败，${this.maxErrorCount - this.errorCount}次后自动停止`);
                }
            } finally {
                this.isLoading = false;
            }
        },
        // 在模板中添加轮询控制按钮（在action-buttons区域添加）
        // <el-button
        // :type="isPolling ? 'warning' : 'success'"
        // :icon="pollingStatusIcon"
        // @click="togglePolling"
        // :loading="isLoading">
        // {{ pollingStatusText }}
        // </el-button>
        // 格式化手机号
        formatPhone(phone) {
            if (!phone) return '未设置';
            return phone.replace(/(\d{3})\d{4}(\d{4})/, '$1****$2');
        },
        // 格式化日期
        formatDate(date) {
            if (!date) return '从未登录';
            return new Date(date).toLocaleString('zh-CN');
        },
        // 角色颜色映射
        getRoleColor(uid) {
            const colorMap = {
                'admin': 'danger',
                'vip': 'warning',
                'user': 'success'
            };
            return colorMap[uid] || 'info';
        },
        // 角色文本映射
        getRoleText(uid) {
            const textMap = {
                '管理员': '管理员',
                'vip用户': 'VIP用户',
                '普通用户': '普通用户'
            };
            return textMap[uid] || '未知角色';
        },
        // 获取状态文本
        getStatusText(status) {
            return status === 1 ? '已禁用' : '已启用';
        },
        // 获取状态标签颜色
        getStatusType(status) {
            return status === 1 ? 'danger' : 'success';
        },
        // 表格行类名
        tableRowClassName({ rowIndex }) {
            return rowIndex % 2 === 1 ? 'striped-row' : '';
        },
        // 选择改变
        handleSelectionChange(selection) {
            this.multipleSelection = selection;
        },
        // 页码改变
        async handlePageChange(newPage) {
            this.currentPage = newPage;
            if (!this.isSearching) {
                await this.loadData();
            }
        },
        // 每页大小改变
        async handleSizeChange(newSize) {
            this.pageSize = newSize;
            this.currentPage = 1;
            if (!this.isSearching) {
                await this.loadData();
            }
        },
        // 搜索方法
        async handleSearch() {
            console.log('searchValue', this.searchType);

            this.currentPage = 1;
            this.isSearching = true;
            this.listLoading = true;
            try {
                const data = {
                    imformationWord: this.searchValue.trim(),
                    currentPage: this.currentPage,
                    status: this.filters.status,
                    searchType: this.searchType
                };
                const res = await GetByImportanceKey(data);
                if (res && res.data) {
                    this.searchResultData = res.data.records || [];
                } else {
                    this.searchResultData = [];
                }
            } catch (error) {
                console.error("搜索失败:", error);
                this.$message.error('搜索失败');
                this.searchResultData = [];
            } finally {
                this.listLoading = false;
            }
        },
        // 清空搜索框
        async handleClear() {
            this.filters.name = '';
            this.isSearching = false;
            this.currentPage = 1;
            await this.loadData();
        },
        // 重置搜索条件
        async handleRefresh() {
            this.filters = {
                name: '',
                status: '',
                uid: ''
            };
            this.currentPage = 1;
            this.isSearching = false;
            await this.loadData();
        },
        // 加载统计数据
        async loadStatistics() {
            try {
                const today = new Date().toISOString().split('T')[0];
                const activeRes = await getActiveUserNumberByDate(today);
                if (activeRes && activeRes.data && activeRes.data.data !== undefined) {
                    this.activeUserCount = activeRes.data.data;
                }
            } catch (error) {
                console.error('加载统计数据失败:', error);
                this.calculateBasicStatistics();
            }
        },
        // 基础统计计算
        calculateBasicStatistics() {
            this.activeUserCount = this.tableData.filter(item => item.status === 0).length;
            this.inactiveUserCount = this.tableData.filter(item => item.status === 1).length;
            this.onlineUserCount = this.tableData.filter(item => item.isOnline).length;
        },
        // 添加用户
        handleAdd() {
            this.$router.push('/home/addUser');
        },
        // 编辑用户
        handleEdit(id) {
            this.$router.push(`/home/UpUser/${id}`);
        },
        // 查看详情
        async handleView(row) {
            try {
                this.listLoading = true;
                const res = await getUserById(row.id);
                if (res.data.code === 1) {
                    this.currentUser = res.data.data;
                    this.detailDialogVisible = true;
                }
            } catch (error) {
                console.error('获取用户详情失败:', error);
                this.$message.error('获取用户详情失败');
            } finally {
                this.listLoading = false;
            }
        },
        // 关闭详情弹窗
        closeDetailDialog() {
            this.detailDialogVisible = false;
            this.currentUser = null;
        },
        // 重置密码
        async handleResetPassword(id) {
            try {
                await this.$confirm('确定要重置该用户的密码吗？重置后密码为123456', '重置密码确认', {
                    type: 'warning',
                    confirmButtonText: '确定重置',
                    cancelButtonText: '取消'
                });
                await UpUser({ id, password: '123456' });
                this.$message.success('密码重置成功');
                if (this.isSearching) {
                    await this.handleSearch();
                } else {
                    await this.loadData();
                }
                await this.loadStatistics();
            } catch (error) {
                if (error !== 'cancel') {
                    this.$message.error('密码重置失败');
                }
            }
        },
        // 批量删除
        async handleBatchDelete() {
            if (this.multipleSelection.length === 0) {
                this.$message.warning('请选择要删除的用户');
                return;
            }
            try {
                await this.$confirm(
                    `确定删除选中的 ${this.multipleSelection.length} 个用户吗？此操作不可恢复！`,
                    '批量删除确认',
                    {
                        type: 'warning',
                        confirmButtonText: '确定删除',
                        cancelButtonText: '取消'
                    }
                );
                const ids = this.multipleSelection.map(item => item.id);
                await batchDelete(ids);
                if (this.isSearching) {
                    await this.handleSearch();
                } else {
                    await this.loadData();
                }
                await this.loadStatistics();
                this.$message.success(`成功删除 ${this.multipleSelection.length} 个用户`);
                this.multipleSelection = [];
            } catch (error) {
                if (error !== 'cancel') {
                    this.$message.error('删除失败，请重试');
                }
            }
        },
        // 删除单个用户
        async handleDelete(id) {
            try {
                await this.$confirm('确定删除该用户吗？此操作不可恢复！', '删除确认', {
                    type: 'warning',
                    confirmButtonText: '确定删除',
                    cancelButtonText: '取消'
                });
                await handleDeleteUser(id);
                if (this.isSearching) {
                    await this.handleSearch();
                } else {
                    await this.loadData();
                }
                await this.loadStatistics();
                this.$message.success('删除成功');
            } catch (error) {
                if (error !== 'cancel') {
                    this.$message.error('删除失败，请重试');
                }
            }
        },
        // 修改用户状态 - 修复版本
        async handleStatusChange(id, status) {
            console.log('切换状态:', id, status);
            // 保存旧状态，用于失败回滚
            const oldStatus = status === 0 ? 1 : 0;
            try {
                // 正确传参：两个参数，不是对象！
                await modifyStatus(id, status);
                this.$message.success('状态更新成功');
                // 刷新数据
                if (this.isSearching) {
                    await this.handleSearch();
                } else {
                    await this.loadData();
                }
                await this.loadStatistics();
            } catch (error) {
                // 回滚 UI
                const dataSource = this.isSearching ? this.searchResultData : this.tableData;
                const item = dataSource.find(item => item.id === id);
                if (item) {
                    this.$nextTick(() => {
                        item.status = oldStatus;
                    });
                }
                this.$message.error('状态更新失败');
                console.error('状态更新失败:', error);
            }
        },
        // 导出数据
        handleExport() {
            this.$message.info('导出功能开发中...');
        },
        // 下拉菜单命令
        handleDropdownCommand(command) {
            switch (command) {
                case 'profile':
                    this.$message.info('个人资料功能开发中...');
                    break;
                case 'upload':
                    this.triggerFileUpload();
                    break;
                case 'settings':
                    this.$message.info('系统设置功能开发中...');
                    break;
                case 'logout':
                    this.handleLogout();
                    break;
            }
        },
        // 退出登录
        async handleLogout() {
            try {
                await this.$confirm('确定要退出登录吗？', '退出确认', { type: 'warning' });
                this.$store.dispatch('user/logout');
                this.$router.push('/login');
            } catch (error) {
                // 取消操作
            }
        },
        // 头像错误处理
        handleAvatarError() {
            this.$store.commit('user/UPDATE_AVATAR', '/default-avatar.png');
        },
        // 触发文件上传
        triggerFileUpload() {
            this.$refs.fileInput.click();
        },
        // 文件改变处理
        async handleFileChange(e) {
            const file = e.target.files[0];
            if (!file) return;
            const isJPG = file.type === 'image/jpeg' || file.type === 'image/png';
            const isLt2M = file.size / 1024 / 1024 < 2;
            if (!isJPG) {
                this.$message.error('上传头像图片只能是 JPG/PNG 格式!');
                return;
            }
            if (!isLt2M) {
                this.$message.error('上传头像图片大小不能超过 2MB!');
                return;
            }
            try {
                this.listLoading = true;
                const formData = new FormData();
                formData.append('file', file);
                const res = await upload(formData);
                this.$store.commit('user/UPDATE_AVATAR', res.data.url);
                this.$message.success('头像更新成功');
            } catch (error) {
                this.$message.error('头像更新失败');
            } finally {
                this.listLoading = false;
                this.$refs.fileInput.value = '';
            }
        },
        // 加载用户列表数据
        async loadData() {
            this.listLoading = true;
            try {
                const response = await getUserList(this.currentPage);
                console.log('response', response);
                if (response && response.data && response.data.data) {
                    this.tableData = response.data.data.records || [];
                    this.total = response.data.data.total || 0;
                    await this.loadStatistics();
                } else {
                    this.tableData = [];
                    this.total = 0;
                    this.calculateBasicStatistics();
                }
            } catch (error) {
                console.error('获取用户列表失败:', error);
                this.$message.error('数据加载失败');
                this.tableData = [];
                this.total = 0;
                this.calculateBasicStatistics();
            } finally {
                this.listLoading = false;
            }
        }
    },
    beforeUnmount() {
        this.stopPolling();
    },
    async mounted() {
        await this.loadData();
        // 可选：页面加载后自动启动轮询
        this.startPolling();
    }
}
</script>
<style lang="less" scoped>
/* 你原来的全部炫彩 CSS 直接粘贴这里，一行不改！ */
.main-container {
    padding: 24px;
    background: linear-gradient(135deg, #f5f7fa 0%, #c3cfe2 100%);
    min-height: calc(100vh - 60px);

    .header-wrapper {
        display: flex;
        justify-content: space-between;
        align-items: center;
        margin-bottom: 24px;
        background: #fff;
        padding: 20px 24px;
        border-radius: 16px;
        box-shadow: 0 8px 32px rgba(0, 0, 0, 0.1);

        .page-title h1 {
            margin: 0 0 8px 0;
            font-size: 28px;
            font-weight: 700;
            background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
            -webkit-background-clip: text;
            -webkit-text-fill-color: transparent;
        }

        .page-title p {
            margin: 0;
            color: #8590a6;
            font-size: 14px;
        }

        .user-profile .avatar-wrapper {
            display: flex;
            align-items: center;
            gap: 12px;
            cursor: pointer;
            padding: 8px 16px;
            border-radius: 12px;
            transition: all 0.3s ease;

            &:hover {
                background: rgba(102, 126, 234, 0.1);
            }

            .user-avatar {
                width: 48px;
                height: 48px;
                border: 3px solid #667eea;
            }

            .dropdown-icon {
                color: #8590a6;
                transition: transform 0.3s;
            }

            &:hover .dropdown-icon {
                transform: rotate(180deg);
            }
        }
    }

    .stats-section {
        display: grid;
        grid-template-columns: repeat(auto-fit, minmax(200px, 1fr));
        gap: 20px;
        margin-bottom: 24px;

        .stat-card {
            background: #fff;
            padding: 24px;
            border-radius: 16px;
            box-shadow: 0 8px 32px rgba(0, 0, 0, 0.1);
            display: flex;
            gap: 16px;
            transition: all 0.3s;

            &:hover {
                transform: translateY(-4px);
            }

            .stat-icon {
                width: 60px;
                height: 60px;
                border-radius: 16px;
                display: flex;
                align-items: center;
                justify-content: center;
                font-size: 24px;
                color: #fff;

                &.total {
                    background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
                }

                &.active {
                    background: linear-gradient(135deg, #56ab2f 0%, #a8e6cf 100%);
                }

                &.inactive {
                    background: linear-gradient(135deg, #ff416c 0%, #ff4b2b 100%);
                }

                &.online {
                    background: linear-gradient(135deg, #4facfe 0%, #00f2fe 100%);
                }
            }

            .stat-value {
                font-size: 32px;
                font-weight: 700;
                color: #2d3748;
            }

            .stat-label {
                font-size: 14px;
                color: #8590a6;
            }
        }
    }

    .action-section {
        background: #fff;
        padding: 24px;
        border-radius: 16px;
        box-shadow: 0 8px 32px rgba(0, 0, 0, 0.1);
        margin-bottom: 24px;
        display: flex;
        justify-content: space-between;
        align-items: flex-end;
        flex-wrap: wrap;
        gap: 16px;

        .search-filters {
            flex: 1;
            min-width: 300px;

            .universal-search {
                width: 480px;
                max-width: 100%;
            }

            .search-tips {
                margin-top: 8px;
                display: flex;
                gap: 8px;
                flex-wrap: wrap;
            }
        }

        .action-buttons {
            display: flex;
            gap: 12px;
            flex-wrap: wrap;

            .el-button {
                font-weight: 600;
            }
        }
    }

    .table-section {
        background: #fff;
        border-radius: 16px;
        box-shadow: 0 8px 32px rgba(0, 0, 0, 0.1);
        overflow: hidden;
        margin-bottom: 24px;

        .custom-table {
            &.el-table--striped .striped-row {
                background: rgba(102, 126, 234, 0.05);
            }

            .avatar-cell {
                position: relative;

                .online-indicator {
                    position: absolute;
                    bottom: 5px;
                    right: 15px;
                    width: 12px;
                    height: 12px;
                    background: #10b981;
                    border: 2px solid #fff;
                    border-radius: 50%;
                }
            }
        }
    }

    .pagination-section {
        background: #fff;
        padding: 20px 24px;
        border-radius: 16px;
        box-shadow: 0 8px 32px rgba(0, 0, 0, 0.1);
        display: flex;
        justify-content: space-between;
        align-items: center;
    }
}

@media (max-width: 768px) {
    .action-section {
        flex-direction: column;
        align-items: stretch;
    }

    .universal-search {
        width: 100%;
    }

    .search-tips {
        justify-content: center;
    }
}
</style>
<style lang="less" scoped>
/* 搜索区域样式优化 */
.search-filters {
    display: flex;
    flex-wrap: wrap;
    gap: 12px;
    align-items: flex-start;
}

.search-input,
.filter-select,
.date-picker {
    width: 180px;
}

.advanced-search-section {
    margin-top: 15px;
    padding: 15px;
    background: #f8f9fa;
    border-radius: 6px;
    border: 1px solid #e9ecef;
}

.advanced-filter-item {
    display: flex;
    align-items: center;
    gap: 8px;
}

.filter-label {
    font-size: 12px;
    color: #606266;
    white-space: nowrap;
    min-width: 80px;
}

.number-input,
.small-select,
.small-input {
    width: 100px;
}

.range-separator {
    color: #909399;
    margin: 0 5px;
}

.search-buttons {
    display: flex;
    align-items: center;
    gap: 10px;
}

.advanced-toggle {
    margin-left: 10px;
    font-size: 12px;
}

.action-buttons {
    margin-top: 15px;
    display: flex;
    gap: 10px;
}

/* 响应式设计 */
@media (max-width: 1200px) {
    .search-filters {
        gap: 8px;
    }

    .search-input,
    .filter-select,
    .date-picker {
        width: 160px;
    }
}

.main-container {
    padding: 24px;
    background: linear-gradient(135deg, #f5f7fa 0%, #c3cfe2 100%);
    min-height: calc(100vh - 60px);

    // 头部区域
    .header-wrapper {
        display: flex;
        justify-content: space-between;
        align-items: center;
        margin-bottom: 24px;
        background: #fff;
        padding: 20px 24px;
        border-radius: 16px;
        box-shadow: 0 8px 32px rgba(0, 0, 0, 0.1);

        .page-title {
            h1 {
                margin: 0 0 8px 0;
                font-size: 28px;
                font-weight: 700;
                background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
                -webkit-background-clip: text;
                -webkit-text-fill-color: transparent;
            }

            p {
                margin: 0;
                color: #8590a6;
                font-size: 14px;
            }
        }

        .user-profile {
            .avatar-wrapper {
                display: flex;
                align-items: center;
                gap: 12px;
                cursor: pointer;
                padding: 8px 16px;
                border-radius: 12px;
                transition: all 0.3s ease;

                &:hover {
                    background: rgba(102, 126, 234, 0.1);
                }

                .user-avatar {
                    width: 48px;
                    height: 48px;
                    border: 3px solid #667eea;
                    transition: transform 0.3s ease;
                }

                .user-info {
                    display: flex;
                    flex-direction: column;

                    .user-name {
                        font-size: 16px;
                        font-weight: 600;
                        color: #2d3748;
                    }

                    .user-uid {
                        font-size: 12px;
                        color: #8590a6;
                    }
                }

                .dropdown-icon {
                    color: #8590a6;
                    transition: transform 0.3s ease;
                }

                &:hover .dropdown-icon {
                    transform: rotate(180deg);
                }
            }
        }
    }

    // 统计卡片区域
    .stats-section {
        display: grid;
        grid-template-columns: repeat(auto-fit, minmax(200px, 1fr));
        gap: 20px;
        margin-bottom: 24px;

        .stat-card {
            background: #fff;
            padding: 24px;
            border-radius: 16px;
            box-shadow: 0 8px 32px rgba(0, 0, 0, 0.1);
            display: flex;
            align-items: center;
            gap: 16px;
            transition: all 0.3s ease;

            &:hover {
                transform: translateY(-4px);
                box-shadow: 0 12px 48px rgba(0, 0, 0, 0.15);
            }

            .stat-icon {
                width: 60px;
                height: 60px;
                border-radius: 16px;
                display: flex;
                align-items: center;
                justify-content: center;
                font-size: 24px;
                color: #fff;

                &.total {
                    background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
                }

                &.active {
                    background: linear-gradient(135deg, #56ab2f 0%, #a8e6cf 100%);
                }

                &.inactive {
                    background: linear-gradient(135deg, #ff416c 0%, #ff4b2b 100%);
                }

                &.online {
                    background: linear-gradient(135deg, #4facfe 0%, #00f2fe 100%);
                }
            }

            .stat-content {
                flex: 1;

                .stat-value {
                    font-size: 32px;
                    font-weight: 700;
                    color: #2d3748;
                    line-height: 1;
                    margin-bottom: 4px;
                }

                .stat-label {
                    font-size: 14px;
                    color: #8590a6;
                    font-weight: 500;
                }
            }
        }
    }

    // 操作区域
    .action-section {
        background: #fff;
        padding: 24px;
        border-radius: 16px;
        box-shadow: 0 8px 32px rgba(0, 0, 0, 0.1);
        margin-bottom: 24px;
        display: flex;
        justify-content: space-between;
        align-items: flex-end;
        flex-wrap: wrap;
        gap: 16px;

        .search-filters {
            display: flex;
            gap: 12px;
            flex-wrap: wrap;
            align-items: center;

            .search-input {
                width: 280px;
            }

            .filter-select {
                width: 140px;
            }
        }

        .action-buttons {
            display: flex;
            gap: 12px;
            flex-wrap: wrap;

            .add-btn {
                background: linear-gradient(135deg, #56ab2f 0%, #a8e6cf 100%);
                border: none;
                color: #fff;
                font-weight: 600;

                &:hover {
                    background: linear-gradient(135deg, #4a9628 0%, #96d9bb 100%);
                }
            }

            .batch-delete-btn {
                background: linear-gradient(135deg, #ff416c 0%, #ff4b2b 100%);
                border: none;
                color: #fff;
                font-weight: 600;

                &:hover:not(:disabled) {
                    background: linear-gradient(135deg, #e63946 0%, #e63946 100%);
                }

                &:disabled {
                    opacity: 0.5;
                    cursor: not-allowed;
                }
            }
        }
    }

    // 表格区域
    .table-section {
        background: #fff;
        border-radius: 16px;
        box-shadow: 0 8px 32px rgba(0, 0, 0, 0.1);
        overflow: hidden;
        margin-bottom: 24px;

        .custom-table {
            border-radius: 16px;

            &.el-table--striped .striped-row {
                background: rgba(102, 126, 234, 0.05);
            }

            .avatar-cell {
                position: relative;
                display: flex;
                justify-content: center;
                align-items: center;

                .user-table-avatar {
                    border: 2px solid #e2e8f0;
                    transition: transform 0.3s ease;

                    &:hover {
                        transform: scale(1.1);
                    }
                }

                .online-indicator {
                    position: absolute;
                    bottom: 5px;
                    right: 15px;
                    width: 12px;
                    height: 12px;
                    background: #10b981;
                    border: 2px solid #fff;
                    border-radius: 50%;
                    box-shadow: 0 0 6px rgba(16, 185, 129, 0.5);
                }
            }

            .user-name-cell {
                .user-name {
                    font-weight: 600;
                    color: #2d3748;
                    display: block;
                    margin-bottom: 4px;
                }

                .user-tags {
                    display: flex;
                    gap: 4px;
                    flex-wrap: wrap;
                }
            }

            .email-text {
                color: #4a5568;
                font-size: 13px;
            }

            .phone-text {
                font-family: 'Monaco', 'Consolas', monospace;
                color: #4a5568;
                font-size: 13px;
            }

            .time-text {
                color: #8590a6;
                font-size: 12px;
            }

            .action-buttons-cell {
                display: flex;
                gap: 6px;
                justify-content: center;
            }
        }
    }

    // 分页区域
    .pagination-section {
        background: #fff;
        padding: 20px 24px;
        border-radius: 16px;
        box-shadow: 0 8px 32px rgba(0, 0, 0, 0.1);
        display: flex;
        justify-content: space-between;
        align-items: center;

        .pagination-info {
            color: #8590a6;
            font-size: 14px;
        }
    }

    // 用户详情弹窗
    .user-detail {
        .detail-header {
            display: flex;
            gap: 20px;
            margin-bottom: 20px;
            align-items: center;

            .detail-avatar {
                position: relative;
                flex-shrink: 0;

                .detail-user-avatar {
                    border: 3px solid #e2e8f0;
                }

                .online-badge {
                    position: absolute;
                    bottom: -5px;
                    right: -5px;
                    background: #10b981;
                    color: #fff;
                    padding: 2px 8px;
                    border-radius: 12px;
                    font-size: 10px;
                    font-weight: 600;
                    box-shadow: 0 2px 8px rgba(16, 185, 129, 0.3);
                }
            }

            .detail-info {
                flex: 1;

                h3 {
                    margin: 0 0 8px 0;
                    font-size: 24px;
                    font-weight: 700;
                    color: #2d3748;
                }

                .user-email {
                    color: #8590a6;
                    margin: 0 0 12px 0;
                    font-size: 14px;
                }

                .user-status-tags {
                    display: flex;
                    gap: 8px;
                    flex-wrap: wrap;
                }
            }
        }

        .detail-content {
            p {
                margin: 8px 0;
                line-height: 1.6;
                color: #4a5568;

                strong {
                    color: #2d3748;
                    font-weight: 600;
                }
            }

            .user-bio {
                margin-top: 20px;
                padding-top: 20px;
                border-top: 1px solid #e2e8f0;

                p:last-child {
                    background: #f7fafc;
                    padding: 16px;
                    border-radius: 8px;
                    margin: 12px 0 0 0;
                    color: #4a5568;
                    line-height: 1.6;
                }
            }
        }
    }
}

// 自定义下拉菜单样式
:deep(.custom-dropdown) {
    border-radius: 12px;
    box-shadow: 0 12px 48px rgba(0, 0, 0, 0.15);

    .el-dropdown-menu__item {
        padding: 12px 20px;
        font-size: 14px;

        &:hover {
            background: rgba(102, 126, 234, 0.1);
            color: #667eea;
        }

        &.is-divided {
            border-top: 1px solid #e2e8f0;
        }
    }
}

// 响应式设计
@media (max-width: 768px) {
    .main-container {
        padding: 16px;

        .header-wrapper {
            flex-direction: column;
            gap: 16px;
            text-align: center;

            .page-title h1 {
                font-size: 24px;
            }
        }

        .stats-section {
            grid-template-columns: repeat(2, 1fr);
        }

        .action-section {
            flex-direction: column;
            align-items: stretch;

            .search-filters {
                flex-direction: column;

                .search-input,
                .filter-select {
                    width: 100%;
                }
            }

            .action-buttons {
                justify-content: center;

                .el-button {
                    flex: 1;
                    min-width: 120px;
                }
            }
        }

        .table-section {
            overflow-x: auto;

            .custom-table {
                min-width: 1000px;
            }
        }

        .pagination-section {
            flex-direction: column;
            gap: 16px;
            text-align: center;
        }
    }
}

@media (max-width: 480px) {
    .main-container {
        .stats-section {
            grid-template-columns: 1fr;
        }

        .action-buttons {
            flex-direction: column;

            .el-button {
                width: 100%;
            }
        }
    }
}

// 动画效果
@keyframes fadeInUp {
    from {
        opacity: 0;
        transform: translateY(20px);
    }

    to {
        opacity: 1;
        transform: translateY(0);
    }
}

.main-container>* {
    animation: fadeInUp 0.6s ease-out;
}

.main-container>*:nth-child(1) {
    animation-delay: 0.1s;
}

.main-container>*:nth-child(2) {
    animation-delay: 0.2s;
}

.main-container>*:nth-child(3) {
    animation-delay: 0.3s;
}

.main-container>*:nth-child(4) {
    animation-delay: 0.4s;
}

.main-container>*:nth-child(5) {
    animation-delay: 0.5s;
}
</style>